<template>
    <view class="comm-list-container">
        <!-- 使用封装的页面头部组件 -->
        <page-header title="播种记录"></page-header>

        <view class="search-box">
            <uni-search-bar
                placeholder="请输入要搜索的作物内容"
                v-model="searchKeyword"
                @confirm="handleSearch"
                @input="handleSearch"
                :radius="100"
                cancelButton="none" />
        </view>

        <filter-tabs :activeTab="activeTab" @tab-change="handleFilterChange" />

        <view class="comm-record-list">
            <record-item
                v-for="(item, index) in filteredSeedList"
                :key="index"
                :item="item"
                @clickItem="editSeedRecord(item)"
                @edit="editSeedRecord(item)"
                @delete="confirmDelete(item)">
                <template #header>
                    <view class="item-header">
                        <text class="date-text">
                            {{ formatDate(item.startDate || item.createTime) }}
                        </text>
                        <roc-icon-plus
                            type="fas"
                            name="angle-right"
                            :size="16"
                            color="#2E6140"></roc-icon-plus>
                    </view>
                </template>

                <template #content>
                    <view class="item-content">
                        <div style="display: flex; justify-content: space-between">
                            <view class="info-row">
                                <text class="info-label">地块/条田</text>
                                <text class="info-value">
                                    {{ item.plotName }}-{{ item.fieldName }}
                                </text>
                            </view>

                            <view class="info-row">
                                <text class="info-label">农作物/种子</text>
                                <text class="info-value">{{ getCropAndSeedName(item) }}</text>
                            </view>
                        </div>
                        <view class="info-row">
                            <text class="info-label">备注</text>
                            <text class="info-value">{{ item.remark }}</text>
                        </view>

                        <view class="info-columns">
                            <view class="info-column">
                                <text class="column-label">播种面积</text>
                                <text class="column-value">{{ item.area || 0 }} 亩</text>
                            </view>

                            <view class="info-column">
                                <text class="column-label">播种方式</text>
                                <text class="column-value">
                                    {{ getSowingMethodLabel(item.sowingMethodId) }}
                                </text>
                            </view>
                        </view>

                        <view class="item-images" v-if="item.images">
                            <image
                                v-for="(img, imgIndex) in formatImages(item.images).slice(0, 2)"
                                :key="imgIndex"
                                :src="img"
                                mode="aspectFit"></image>
                        </view>
                    </view>
                </template>
            </record-item>
            <!-- 加载更多提示 -->
            <view class="load-more-container" v-if="filteredSeedList.length > 0">
                <view v-if="loadingMore" class="loading-more">
                    <text class="loading-text">加载中...</text>
                </view>
                <view v-else-if="!hasMore" class="no-more">
                    <text class="no-more-text">没有更多数据了</text>
                </view>
            </view>
        </view>

        <!-- 无数据提示 -->
        <empty-data v-if="filteredSeedList.length === 0" />

        <view class="add-button" @click="navigateTo('/pages/agriculture/seedManagement/addSeed')">
            <text class="add-icon">+</text>
        </view>
    </view>
</template>

<script>
import PageHeader from '@/components/PageHeader/index.vue'
import FilterTabs from '@/components/FilterTabs/index.vue'
import RecordItem from '@/components/RecordItem/index.vue'
import EmptyData from '@/components/EmptyData/index.vue'
import { seed } from '@/utils/api/index.js'
// 导入格式化函数
import { formatDateChinese, formatImages } from '@/utils/util.js'
import { mapGetters, mapActions } from 'vuex'

export default {
    components: {
        PageHeader,
        FilterTabs,
        RecordItem,
        EmptyData,
    },
    data() {
        return {
            title: '播种记录',
            activeTab: 'all',
            searchKeyword: '',
            seedList: [],
            loading: false,
            loadingMore: false,
            hasMore: true,
            pageParams: {
                pageNo: 1,
                pageSize: 30,
            },
        }
    },
    computed: {
        ...mapGetters({
            getDictByType: 'getDictByType',
            getDictLabel: 'getDictLabel',
        }),
        filteredSeedList() {
            return this.seedList
        },
    },
    onLoad() {
        // 确保字典数据已加载
        this.loadDictData()
    },
    onShow() {
        this.fetchSeedList()
    },
    // 下拉刷新
    onPullDownRefresh() {
        this.fetchSeedList()
    },
    // 触底加载更多
    onReachBottom() {
        this.loadMoreData()
    },
    methods: {
        ...mapActions(['getDictByType']),

        // 加载字典数据
        async loadDictData() {
            try {
                // 加载农作物类型字典
                await this.getDictByType('crop_name_type')

                // 加载播种方式字典
                await this.getDictByType('seeding_method')

                // 加载播种机械字典
                await this.getDictByType('sowing_machinery')

                // 预加载各种作物的种子字典
                const cropTypes = this.getDictByType('crop_name_type')
                for (const crop of cropTypes) {
                    if (crop.value) {
                        await this.getDictByType(crop.value)
                    }
                }
            } catch (error) {
                console.error('加载字典数据失败:', error)
            }
        },

        // 获取农作物和种子名称的显示文本
        getCropAndSeedName(item) {
            if (!item.cropType && !item.seedName) return '未指定'

            const cropLabel =
                this.getDictLabel('crop_name_type', item.cropType) || item.cropType || ''
            let seedLabel = item.seedName || ''

            // 如果有作物类型，尝试从对应的种子字典中获取种子名称
            if (item.cropType && item.seedName) {
                seedLabel = this.getDictLabel(item.cropType, item.seedId) || item.seedName
            }

            if (cropLabel && seedLabel) {
                return `${cropLabel}-${seedLabel}`
            } else if (cropLabel) {
                return cropLabel
            } else if (seedLabel) {
                return seedLabel
            }

            return '未指定'
        },

        // 获取播种方式的显示文本
        getSowingMethodLabel(value) {
            if (!value) return '无人机' // 默认值
            return this.getDictLabel('seeding_method', value) || value
        },

        // 处理筛选变化
        handleFilterChange(tabValue, filterData) {
            this.activeTab = tabValue

            // 重置页码
            this.pageParams.pageNo = 1
            this.hasMore = true // 重置加载更多状态

            // 清除之前的日期和地块筛选条件
            delete this.pageParams.startDate
            delete this.pageParams.endDate
            delete this.pageParams.areaId

            // 添加新的筛选条件
            if (filterData) {
                if (filterData.startDate && filterData.endDate) {
                    this.pageParams.startDate = filterData.startDate
                    this.pageParams.endDate = filterData.endDate
                }

                if (filterData.areaId) {
                    this.pageParams.plotId = filterData.areaId
                }
            }

            // 重新请求接口
            this.fetchSeedList()
        },

        // 处理搜索变化
        handleSearch(e) {
            console.log('handleSearch', e)
            // 重置页码
            this.pageParams.pageNo = 1
            this.hasMore = true // 重置加载更多状态

            // 更新关键词搜索参数
            if (this.searchKeyword) {
                this.pageParams.keyword = e || this.searchKeyword
            } else {
                delete this.pageParams.keyword
            }

            // 重新请求接口
            this.fetchSeedList()
        },

        async fetchSeedList(isLoadMore = false) {
            try {
                if (isLoadMore) {
                    this.loadingMore = true
                } else {
                    this.loading = true
                    uni.showLoading({ title: '加载中...' })
                }

                const res = await seed.getSeedPage(this.pageParams)

                if (res.code === 0 && res.data) {
                    const newList = res.data.list || []

                    if (isLoadMore) {
                        // 加载更多时追加数据
                        this.seedList = [...this.seedList, ...newList]
                        // 判断是否还有更多数据
                        this.hasMore = newList.length >= this.pageParams.pageSize
                    } else {
                        // 首次加载或刷新时替换数据
                        this.seedList = newList
                        this.hasMore = newList.length >= this.pageParams.pageSize
                    }
                } else {
                    // 如果API请求失败，使用默认数据
                    if (!isLoadMore) {
                        this.seedList = this.getDefaultData()
                    }
                }
            } catch (error) {
                console.error('获取播种记录失败:', error)
                if (!isLoadMore) {
                    uni.showToast({
                        title: '获取数据失败',
                        icon: 'none',
                    })
                    // 使用默认数据
                    this.seedList = this.getDefaultData()
                }
            } finally {
                this.loading = false
                this.loadingMore = false
                uni.hideLoading()
                uni.stopPullDownRefresh()
            }
        },

        // 获取默认数据，在API请求失败时使用
        getDefaultData() {
            return [
                // {
                //     id: 1,
                //     type: "rice",
                //     cropType: "rice",
                //     name: "0",
                //     seedName: "0",
                //     field: "1号地块",
                //     plotId: "1",
                //     fieldId: "1",
                //     plotName: "1号地块",
                //     fieldName: "1号条田",
                //     area: 45.3,
                //     sowingMethod: "0",
                //     startDate: "2023-11-15 09:30",
                //     personInCharge: "张明远",
                //     images: "/static/agriculture/seed/rice1.jpg",
                // },
            ]
        },

        navigateTo(url) {
            uni.navigateTo({
                url,
            })
        },

        formatDate(dateString) {
            return formatDateChinese(dateString)
        },

        formatImages(imagesStr) {
            return formatImages(imagesStr)
        },

        viewDetail(item) {
            // 跳转到详情页面
            uni.navigateTo({
                url: `/pages/agriculture/seedManagement/addSeed?id=${item.id}`,
            })
        },

        editSeedRecord(item) {
            // 编辑记录，跳转到编辑页面
            uni.navigateTo({
                url: `/pages/agriculture/seedManagement/addSeed?id=${item.id}`,
            })
        },

        confirmDelete(item) {
            uni.showModal({
                title: '确认删除',
                content: `确定要删除这条播种记录吗？`,
                success: (res) => {
                    if (res.confirm) {
                        this.deleteSeedRecord(item.id)
                    }
                },
            })
        },

        async deleteSeedRecord(id) {
            try {
                uni.showLoading({ title: '删除中...' })

                const res = await seed.deleteSeedRecord(id)

                if (res.code === 0 && res.data) {
                    // 删除成功，更新列表
                    const index = this.seedList.findIndex((item) => item.id === id)
                    if (index !== -1) {
                        this.seedList.splice(index, 1)
                    }

                    uni.showToast({
                        title: '删除成功',
                        icon: 'success',
                    })
                } else {
                    uni.showToast({
                        title: res.msg || '删除失败',
                        icon: 'none',
                    })
                }
            } catch (error) {
                console.error('删除播种记录失败:', error)
                uni.showToast({
                    title: '删除失败',
                    icon: 'none',
                })
            } finally {
                uni.hideLoading()
            }
        },

        // 加载更多数据
        loadMoreData() {
            if (this.loadingMore || !this.hasMore) {
                return
            }

            this.pageParams.pageNo += 1
            this.fetchSeedList(true)
        },
    },
}
</script>

<style lang="scss"></style>
